package com.yu.boot.admin.web;

import com.yu.boot.admin.model.Category;
import com.yu.boot.admin.model.CategoryCover;
import com.yu.boot.admin.service.CategoryCoverService;
import com.yu.boot.admin.service.CategoryService;
import com.yu.boot.lib.util.AuthUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

@RequestMapping("export")
@Controller
@Slf4j
public class ExportController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategoryCoverService categoryCoverService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @RequestMapping("view")
    public String view() {
        return "export";
    }

    @RequestMapping("")
    @SneakyThrows
    public ResponseEntity<String> export(Category bean) {
        String userName = AuthUtil.getUserName(request);
        if (StringUtils.isEmpty(bean.getCover())) {
            bean.setCover(null);
        }
        bean.setParentName(userName);
        List<Category> categories = categoryService.listCategory(bean);
        List<CategoryCover> categoryCovers = categoryCoverService.listByUserId(AuthUtil.getUser(request).getId());
        @Cleanup InputStream resourceAsStream = this.getClass().getResourceAsStream("/export/temp.html");
        List<String> strings = org.apache.commons.io.IOUtils.readLines(resourceAsStream, "utf-8");
        StringBuilder sb1 = new StringBuilder();
        for (String string : strings) {
            sb1.append(string+"\n");
        }
        Set<String> covers = new TreeSet<>();
        for (Category category : categories) {
            covers.add(category.getCover());
        }
        StringBuilder sb = new StringBuilder();
        for (String cover : covers) {
            sb.append("<div class=\"cover\">\n");
            String coverName = getCoverNameByid(categoryCovers, Integer.valueOf(cover));
            sb.append("    <h3 data-id=\"" + cover + "\">" + coverName + "</h3>\n");
            sb.append("    <ul style=\"width: 100%;\">\n");
            for (Category category : categories) {
                if (category.getCover().equals(cover)) {
                    sb.append("     <li>\n" +
                            "        <a href=\"" + category.getAncestors() + "\" title=\"" + category.getDescription() + "\">" + category.getName() + "</a>\n" +
                            "        <p>"+category.getDescription()+"</p>\n" +
                            "       </li>\n");
                }
            }
            sb.append("    </ul>\n");
            sb.append("</div>\n");
        }
        String replace = sb1.toString().replace("#{body}", sb.toString());
        log.info("create html:{}", replace);
        String filename = "discovery.html";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="
                + filename + "");
        return new ResponseEntity<>(replace, headers, HttpStatus.CREATED);
    }

    public String getCoverNameByid(List<CategoryCover> categoryCovers, Integer id) {
        try {
            String coverName = categoryCovers.stream().filter(cover -> id.equals(cover.getId())).findFirst().get().getCoverName();
            return coverName;
        } catch (Exception e) {
            log.error("", e);
            return "";
        }
    }
}
